package com.ddwl.gate.service;

import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.gate.constant.MobileConfigConstant;
import com.ddwl.common.constant.MobileConfigEnum;
import com.ddwl.gate.dao.MobileRechargeAccountDao;
import com.ddwl.gate.feign.BoHuanClient;
import com.ddwl.gate.model.BohuanCallRecord;
import com.ddwl.gate.model.MobileRechargeAccount;
import com.ddwl.gate.util.boHuan.BoHuanRechargeUtil;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.gate.MobileRechargeConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hemiaojun
 * @Date 2020/9/23 20:18
 */
@Slf4j
@Service
public class MobileRechargeAccountService {

    @Resource
    private MobileRechargeAccountDao mobileRechargeAccountDao;
    @Resource
    private BoHuanClient boHuanClient;
    @Resource
    private MobileRechargeConfigService mobileRechargeConfigService;
    @Resource
    private BohuanCallRecordService bohuanCallRecordService;


    @Transactional(rollbackFor = Exception.class)
    public List<MobileRechargeConfigVo> check() throws Exception{
        MobileRechargeAccount entity =mobileRechargeAccountDao.getByUserIdAndKey();
        if (null != entity.getGmtModified() && (DateUtil.getSpecifiedTime(entity.getGmtModified(), MobileConfigConstant.QUERY_INTERVAL).compareTo(Instant.now()) < 0)) {
            queryBalance();
            entity = mobileRechargeAccountDao.getByUserIdAndKey();
        }
        BigDecimal balance = null == entity.getBalance() ? BigDecimal.ZERO : entity.getBalance();
        BigDecimal credit = null == entity.getCredit() ? BigDecimal.ZERO : entity.getCredit();
        BigDecimal amount = balance.add(credit).setScale(4);
        if (MobileConfigConstant.BALANCE_THRESHOLD.compareTo(amount) < 0 ) {
            return mobileRechargeConfigService.listByMobile(MobileConfigEnum.OperatorEnum.OTHER.getCode());
        }
        return null;
    }

    private void updateAccount(BigDecimal balance,BigDecimal credit) {
        MobileRechargeAccount mra = new MobileRechargeAccount();
        if (null != balance) {
            mra.setBalance(balance);
        }
        if (null != credit) {
            mra.setCredit(credit);
        }
        mobileRechargeAccountDao.updateAccount(mra);
    }

    public void queryBalance() throws Exception{
        HashMap<String, String> map = new HashMap<>(16);
        BoHuanRechargeUtil.queryBalanceAddSign(map);
        log.info("bohuan queryBalance param {}", JSON.toJSONString(map));
        String result=boHuanClient.queryBalance(map);
        log.info("bohuan queryBalance result {}",result);
        JSONObject obj=JSONObject.parseObject(result);
        Integer code = obj.getInteger("nRtn");
        BigDecimal balance;
        BigDecimal credit;
        if (MobileConfigConstant.SUCCESS_CODE.equals(code)) {
            balance = obj.getBigDecimal("fBalance");
            credit = obj.getBigDecimal("fCredit");
            updateAccount(balance,credit);
        }
        addBohuanCallRecord(obj);
    }

    private void addBohuanCallRecord(JSONObject obj) {
        BohuanCallRecord bcr = new BohuanCallRecord();
        bcr.setCallType(MobileConfigEnum.BohuanCallEnum.BALANCE.getType());
        bcr.setCallName(MobileConfigEnum.BohuanCallEnum.BALANCE.getName());
        bcr.setThirdCode(obj.getInteger("nRtn").toString());
        bcr.setThirdStatus(obj.getString("szRtnCode"));
        bcr.setThirdDesc(obj.getString("szRtnCode"));
        bohuanCallRecordService.add(bcr);
    }

    public void changeId() {
        List<MobileRechargeAccount> list=mobileRechargeAccountDao.getAll();
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, String> map = new HashMap<>();
            for (MobileRechargeAccount mra : list) {
                String id = mra.getId();
                if (id.length() == 11) {
                    long longId = UUIDGenerator.reverseShortUUID(id);
                    map.put(id, String.valueOf(longId));
                }
            }
            if (!CollectionUtils.isEmpty(map)) {
                mobileRechargeAccountDao.changeId(map);
            }
        }
    }

}
